<template>
  <div class="insert-tollgate-form">
    <el-form label-width="100px" ref="formRef" :model="submitForm" :rules="rules" status-icon show-message>
      <el-form-item label="章节名称" prop="chapterName">
        <el-input v-model="submitForm.chapterName" placeholder="请输入章节名称" :maxlength="20" show-word-limit></el-input>
      </el-form-item>
      <el-form-item>
        <div class="flex-row-center width-100-percent">
          <el-button @click="handleFormSubmit" :color="sysConfig.DARK_COLOR" dark class="width-80-percent">提交
          </el-button>
        </div>

      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import {computed, defineEmits, ref, watch,defineProps} from "vue";

import sysConfig from "@/config/index"

import {ElMessage, FormInstance, FormRules} from "element-plus";
import {addChapter, getChapterById, getChaptersById, updateChapter} from "@/api/chapter/ChapterApi";

interface ChapterRuleForm{
  chapterName: string,
}
export interface InsertChapterFormType {
  id:string

  schemeId:string
  chapterName:""

}
let props=defineProps<{
  schemeId:string
  chapterId:string
}>()
let emit = defineEmits<{
  (e: "submit", form: InsertChapterFormType): void
}>()
let submitForm = ref<InsertChapterFormType>({
  id:"0",
  schemeId:"0",
  chapterName:""


})

const rules = ref<FormRules<ChapterRuleForm>>({
  chapterName: [
    { required:true,message:"请输入章节名称",trigger:'blur'},
    {min:1,max:20,message:"章节名限制长度:1~20",trigger: 'blur'}
  ],
})

let formRef=ref<FormInstance>()



function insert(){
  addChapter({
    ...submitForm.value,
    tollgateList:[]
  }).then(resp=>{
    if(resp.code === 200){
      ElMessage({
        type:"success",
        message:"添加成功"
      })
      emit("submit", submitForm.value)
    }
  })
}
function update(){
  updateChapter({
    ...submitForm.value,
    tollgateList:[]
  }).then(resp=>{
    if(resp.code === 200){
      ElMessage({
        type:"success",
        message:"修改成功"
      })
      emit("submit", submitForm.value)
    }
  })
}
function getChapter(){
  getChapterById(props.chapterId).then(resp=>{
    if( resp.code === 200){
      submitForm.value=resp.data
    }
  })
}
function handleFormSubmit() {
  formRef.value?.validate((valid)=>{
    if(valid){
      props.chapterId === '0'?insert():update()
    }
  })

}
watch(()=>props.chapterId,(newV)=>{
  if(props.chapterId !== "0"){
    // 修改，请求数据
    getChapter()
  }

},{immediate:true})

watch(()=>props.schemeId,(newV)=>{
  if(props.chapterId === "0"){
    submitForm.value.schemeId=props.schemeId
  }

},{immediate:true})
</script>

<style scoped lang="less">

</style>